//
//  NewsViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/9/14.
//

import UIKit
import MJRefresh
class NewsViewController: BaseViewController {
    var tableView: BaseTableView!
    var messageBtn: UIButton!
    var newMesRed: UIView!//信息红点
    var hotNewsArray: [HotNewsDataModel] = []//热门资讯
    var columnArray: [CurrentAffairDataModel] = [] //资讯栏目
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.init(hex: 0xF8F9FA)
        self.initNav()
        self.initTableView()
        self.requestGetHotArticle()
        self.requestGetArticleCategoryList()
      
    }
    func initNav(){
        let titleLab = UILabel(frame: CGRect(x: 18, y: NavBarHight - 40, width: 100, height: 30))
        titleLab.textColor = Theme.titleLabColor
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        titleLab.text = MMLocalizedString("latest_news", comment: "最新资讯")
        titleLab.backgroundColor = .white
        self.navBar.addSubview(titleLab)
        self.navBar.wr_setBottomLineHidden(hidden: true)
        
        self.messageBtn = UIButton(frame: CGRect(x: kScreenWidth - 75, y: NavBarHight - 40, width: 30, height: 30))
        self.messageBtn.setImage(UIImage(named: "icon_news_msg"), for: .normal)
        self.messageBtn.contentMode = .scaleAspectFill
        self.messageBtn.addTarget(self, action: #selector(messageBtnAtion), for: .touchUpInside)
        self.navBar.addSubview(self.messageBtn)
        
        
        self.newMesRed = UIView(frame: CGRect(x: self.messageBtn.frame.size.width - 12, y: 4, width: 4, height: 4))
        self.newMesRed.backgroundColor = Theme.redColor
        self.newMesRed.layer.cornerRadius = 2
        self.newMesRed.layer.masksToBounds = true
        self.newMesRed.isHidden = true
        self.messageBtn.addSubview(self.newMesRed)
        
        let setBtn = UIButton(frame: CGRect(x: kScreenWidth - 42, y: NavBarHight - 40, width: 30, height: 30))
        setBtn.setImage(UIImage(named: "icon_news_set"), for: .normal)
        setBtn.addTarget(self, action: #selector(setBtnAntion), for: .touchUpInside)
        self.navBar.addSubview(setBtn)
    }
    
    func initTableView(){
        self.tableView = BaseTableView(frame: CGRect(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - TabbarHeight - NavBarHight), style: .plain)
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 2
        self.tableView.register(HotNewsTableViewCell.self, forCellReuseIdentifier: "HotNewsTableViewCell")//热门资讯
        self.tableView.register(CourseTableViewCell.self, forCellReuseIdentifier: "CourseTableViewCell")//栏目
        self.tableView.backgroundColor = .clear
        self.view.addSubview(self.tableView)
        
        self.addPullRefreash()
    }
    
    /*
     添加头部刷新
     */
    func addPullRefreash(){
        weak var weakSelf = self
        self.tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            weakSelf?.requestGetHotArticle()
            weakSelf?.requestGetArticleCategoryList()
        })
    }
    
    //MARK: - Request
    
    //热门咨询列表
    func requestGetHotArticle(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.hotArticle,objectType: HotNewsModel.self) { data in
            let resultObj = data as! HotNewsModel
            self.tableView.mj_header?.endRefreshing()
            if resultObj.code == "1" {
                self.hotNewsArray = resultObj.data ?? []
            }
            self.tableView.reloadData()
        }error: { err in
            self.tableView.mj_header?.endRefreshing()
        }
    }
    
    //咨询栏目
    func requestGetArticleCategoryList(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.articleCategoryList,objectType: CurrentAffairModel.self) { data in
            let resultObj = data as! CurrentAffairModel
            self.tableView.mj_header?.endRefreshing()
            if resultObj.code == "1" {
                let dataArray = resultObj.data ?? []
                //没有文章列表的过滤
                self.columnArray = dataArray.filter{($0.articleList ?? []).count > 0}
            }
            self.tableView.reloadData()
        }error: { err in
            self.tableView.mj_header?.endRefreshing()
        }
    }

    
    //MARK: - Antion
    //信息
   @objc func messageBtnAtion(){
       if UserModule.shared.isLogined == false{
           let vc = LoginViewController()
           let loginNavi = BaseNavigationController.init(rootViewController: vc)
           loginNavi.modalPresentationStyle = .overFullScreen
           self.present(loginNavi, animated: true)
           return
       }
       let vc = MessageViewController()
       self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func setBtnAntion(){
        if UserModule.shared.isLogined == false{
            let vc = LoginViewController()
            let loginNavi = BaseNavigationController.init(rootViewController: vc)
            loginNavi.modalPresentationStyle = .fullScreen
            self.present(loginNavi, animated: true)
            return
        }
        let vc = UserCenterViewController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension NewsViewController: UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1 + self.columnArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if self.hotNewsArray.count == 0 && indexPath.section == 0{
            return 0.01
        }
       
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: "HotNewsTableViewCell", for: indexPath) as! HotNewsTableViewCell
            if self.hotNewsArray.count > 0{
                cell.setDataArray(dataArray: self.hotNewsArray)
            }
            return cell

        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: "CourseTableViewCell", for: indexPath) as! CourseTableViewCell
            if  self.columnArray.count > 0{
                let model = self.columnArray[indexPath.section - 1]
                cell.setColumnModel(model: model)
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
          headerView.backgroundColor = .clear
        return headerView
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        footerView.backgroundColor = .clear
        return footerView
    }
    
}
